package com.lanou3g.ptp.api.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.entity.Teacher;
import com.lanou3g.ptp.entity.User;
import com.lanou3g.ptp.student.service.StudentService;
import com.lanou3g.ptp.teacher.service.TeacherService;
import com.lanou3g.ptp.user.service.UserService;
import com.lanou3g.utils.PtpResult;
import com.lanou3g.utils.PtpResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

@Api(description = "教师接口")
@RestController
public class TeacherController {

    @Reference
    private TeacherService teacherService;

    @Reference
    private StudentService studentService;

    @Reference(check = false)
    private UserService userService;

    @ApiOperation("查询所有教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数"),
            @ApiImplicitParam(name = "size", value = "显示条数")
    })
    @GetMapping("/teacher")
    public PtpResult searchAll(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size) {

        PageInfo<Teacher> all = teacherService.findAll(page, size);
        System.out.println(all);
        return PtpResultUtils.ok(all);

    }


    @ApiOperation("根据id查询教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教师Id")
    })
    @GetMapping("/teacher/search/{id}")
    public PtpResult searchById(@PathVariable Long id) {

        Teacher teacher = teacherService.findById(id);
        User user = userService.userById(teacher.getId());

        HashMap<Object, Object> result = new HashMap<>();
        result.put("id", teacher.getId());
        result.put("name", user.getName());
        result.put("gender", teacher.getGender());
        result.put("phone", user.getTel());
        result.put("type", teacher.getType());

        return PtpResultUtils.ok(result);

    }


    @ApiOperation("根据id删除教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "教师Id")
    })
    @DeleteMapping("/teacher/delete/{id}")
    public PtpResult deleteById(@PathVariable Long id) {

        try {
            teacherService.deleteById(id);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }


    @ApiOperation("批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "多个教师id")
    })
    @DeleteMapping("/teacher/{ids}")
    public PtpResult deleteByIds(@PathVariable Long[] ids) {
        teacherService.deleteByIds(ids);
        return PtpResultUtils.ok();
    }


    @ApiOperation("根据教师姓名查询教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "keyword")
    })
    @GetMapping("/teacher/name")
    public PtpResult searchByKeyword(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "size", defaultValue = "10") Integer size,
                                     String keyword) {

        try {
            PageInfo<Teacher> teacherList;
            if (keyword != null && !keyword.trim().equals("")) {
                teacherList = teacherService.findByKeyword(page, size, keyword);
                System.out.println(teacherList);
            } else {
                teacherList = teacherService.findAll(page, size);
            }
            return PtpResultUtils.ok(teacherList);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }


    @ApiOperation("根据id更改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "teacherId")
    })
    @PutMapping("/teacher/update/{id}")
    public PtpResult update(Long id) {

        try {
            teacherService.updateById(id);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }


    @ApiOperation("添加教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "teacherId"),
            @ApiImplicitParam(name = "type", value = "教师类型"),
            @ApiImplicitParam(name = "schoolId", value = "学校Id"),
            @ApiImplicitParam(name = "baseId", value = "基地Id"),
            @ApiImplicitParam(name = "collegeId", value = "学院Id"),
            @ApiImplicitParam(name = "teachSection", value = "教研室"),
            @ApiImplicitParam(name = "createTime", value = "创建时间"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间"),
            @ApiImplicitParam(name = "status", value = "状态")
    })
    @PostMapping("/teacher/add")
    public PtpResult insert(Teacher teacher) {

        try {
            teacherService.insert(teacher);
            return PtpResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }


    @ApiOperation("导出Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "id数组")
    })
    @GetMapping("/teacher/download/{ids}")
    public PtpResult getTeachers(@PathVariable Long[] ids) {

        try {
            List<Teacher> data = teacherService.getData(ids);
            return PtpResultUtils.ok(data);
        } catch (Exception e) {
            e.printStackTrace();
            return PtpResultUtils.error(500);
        }

    }

    @ApiOperation("导入教师Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherUploadFile", value = ".xlsx文件")
    })
    @PostMapping("/teacher/upload")
    public PtpResult inputTeacher(MultipartFile teacherUploadFile) throws IOException {

        String filename = teacherUploadFile.getOriginalFilename();

        if (filename.endsWith(".xlsx")) {
            byte[] bytes = teacherUploadFile.getBytes();
            boolean b = teacherService.excelToTeacherInfo(bytes);
            return PtpResultUtils.ok(b);
        } else {
            return PtpResultUtils.ok("上传文件格式不正确");
        }

    }


    @ApiOperation("导出TeacherExcel模板")
    @GetMapping("/teacher/model")
    public PtpResult modelTeacher(HttpServletResponse response) {

        response.reset();
        response.setContentType("application/msexcel;charset=utf-8");

        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("教师信息样表.xlsx", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] bytes = teacherService.excelTeacherModel();
        try {
            IOUtils.write(bytes, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return PtpResultUtils.ok();

    }


}
